package com.qys.controller.upload;

import com.qys.common.utils.RSAUtil;
import com.qys.controller.entiry.FinalURL;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * Created by fangc on 2019-10-20 17:09
 */
@Controller
public class UploadShowController {
    private final Logger logger = Logger.getLogger(UploadShowController.class);
    @RequestMapping(path = "/file/upload")
    private ModelAndView show(HttpServletRequest request , HttpServletResponse response){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = null;
        HttpResponse httpResponse = null;
        JSONObject result = new JSONObject();
        try {
            httpGet = new HttpGet(FinalURL.AGO_GISTORY_URL);
            JSONObject object = RSAUtil.getReqHeard();
            httpGet.setHeader("X-SID", object.optString("data"));
            httpGet.setHeader("X-Signature", object.optString("sign"));
            httpGet.setHeader("publicKey", object.optString("publicKey"));
            httpResponse = httpClient.execute(httpGet);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity entity = httpResponse.getEntity();
                result = JSONObject.fromObject(EntityUtils.toString(entity));
                String uuid = result.optString("path");
                uuid = uuid.substring(uuid.lastIndexOf("\\") + 1);
                JSONObject json = new JSONObject();
                json.put("FileName" , result.optString("original"));
                json.put("UUID_name" , uuid);
                json.put("size" , result.optString("size"));
                json.put("type" , result.optString("type"));
                String time = result.optString("createdata");
                json.put("Create_time" , time.substring(0 , time.length() -2));
                Cookie cookie = new Cookie("data" , URLEncoder.encode(json.toString()));
                response.addCookie(cookie);
            }
        } catch (Exception e) {
            logger.error("查询最近一次上传：" + e.getMessage());
        } finally {
            try {
                if (httpGet != null)
                    httpGet.clone();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ModelAndView("upload");
    }
}
